﻿using KD.Service.HR.Utility;
using Logistics.Model;
using Logistics.Service;
using Logistics.Utility;
using Logistics.WebApi.Attributes;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Web;
using System.Web.Http;
using System.Web.Script.Serialization;
using System.Security.Cryptography;
using Logistics.Model.QueryModel;
using System.Data;

namespace Logistics.WebApi.Controllers
{

    public class AccountController : ApiController
    {
        private CompanyService companyService = new CompanyService();
        private AccountService service = new AccountService();
        /// <summary>
        /// 
        /// </summary>
        /// <param name="user"></param>
        /// <returns></returns>
        [HttpPost]
        public ResponseModel Login(wuliu_account_base_query user)
        {
            var Resultmod = new ResponseModel();
            var ip = GetUserInfo.GetWebClientIp(); 
            if(string.IsNullOrEmpty(user.registration_id)&&!(user.channel=="200"||user.channel=="300"))
            {

                var usermod = service.GetAccountById(user.account);
                string password = user.password;
                if (usermod != null)
                {
                    if (usermod.password_type == 11)
                    {
                        password = getMd5Hash(usermod.password_key + user.password);
                    }
                    else
                    {
                        if (usermod.password_type == 0)
                        {
                            password = user.password;
                        }
                        else
                        {
                            password = getMd5Hash(user.password);
                        }
                    }
                }

                var account = service.Login(user.account, password, ip);
                if (account != null)
                {
                    string tokenValue = this.getGuidString();
                    wuliu_account_online online = new wuliu_account_online();
                    online.account_id = account.account_id;
                    online.online_key_pc = tokenValue;
                   
                    if (user.savetime > 0)
                    {
                        online.sdatetime = DateConvert.DateTimeToStamp(DateTime.Now);
                        online.edatetime = DateConvert.DateTimeToStamp(DateTime.Now.AddDays(user.savetime));
                    }
                    else
                    {
                        online.edatetime = DateConvert.DateTimeToStamp(DateTime.Now);
                        online.sdatetime = DateConvert.DateTimeToStamp(DateTime.Now.AddDays(1));
                    }
                    
                   var flag= service.Add(online);

                    //HttpContext.Current.Session["LoginUser"] = account;
                    Resultmod.InitResultState(LoginEnum.Success);
                    Resultmod.mod = account;
                    Resultmod.token = tokenValue;
                    CacheManager.TokenInsert(tokenValue, account);
                    //var obj = CacheManager.GetTokenValue(tokenValue);

                    //var flag = CacheManager.TokenClear(tokenValue);
                }
                else
                {
                    Resultmod.InitResultState(LoginEnum.Error01);
                }
            }
            else
            {//手机端登录

                if(!string.IsNullOrEmpty(user.token))
                {
                    var phone = (wuliu_account_base)CacheManager.GetTokenValue(user.token);
                    if(phone!=null)
                    {
                        Resultmod.mod = service.PhoneLogin(phone.account, phone.password);
                        Resultmod.InitResultState(LoginEnum.Success);
                        wuliu_account_online online = new wuliu_account_online();
                        online.account_id = phone.account_id;
                        online.online_key = user.token;

                        if (user.savetime > 0)
                        {
                            online.sdatetime = DateConvert.DateTimeToStamp(DateTime.Now);
                            online.edatetime = DateConvert.DateTimeToStamp(DateTime.Now.AddDays(user.savetime));
                        }
                        else
                        {
                            online.edatetime = DateConvert.DateTimeToStamp(DateTime.Now);
                            online.sdatetime = DateConvert.DateTimeToStamp(DateTime.Now.AddDays(1));
                        }

                        var flag = service.Add(online);

                        if (user.channel == "200")//安卓
                        {
                            wuliu_account_android_token android = new wuliu_account_android_token();
                            android.account_id = phone.account_id;
                            android.android_token = user.registration_id;
                            android.create_time = DateConvert.DateTimeToStamp(DateTime.Now);
                            var fla = service.DelAndroidPhoneToken(phone.account_id.ToString(), user.registration_id);
                            fla = service.DelIOSPhoneToken(phone.account_id.ToString(), user.registration_id);
                            service.AddAndroidPhoneToken(android);
                        }
                        if (user.channel == "300")//IOS
                        {
                            wuliu_account_ios_token ios = new wuliu_account_ios_token();
                            ios.account_id = phone.account_id;
                            ios.ios_token = user.registration_id;
                            ios.create_time = DateConvert.DateTimeToStamp(DateTime.Now);
                            var fla = service.DelAndroidPhoneToken(phone.account_id.ToString(), user.registration_id);
                            fla = service.DelIOSPhoneToken(phone.account_id.ToString(), user.registration_id);
                            service.AddIOSPhoneToken(ios);
                        }
                    }
                    else
                    {
                        Resultmod.InitResultState(LoginEnum.Error03);
                    }
                    

                }
                else
                {
                   
                    var usermod = service.GetAccountById(user.account);
                    string password = user.password;
                    if (usermod != null)
                    {
                        if (usermod.password_type == 11)
                        {
                            password = getMd5Hash(usermod.password_key + user.password);
                        }
                        else
                        {
                            if (usermod.password_type == 0)
                            {
                                password = user.password;
                            }
                            else
                            {
                                password = getMd5Hash(user.password);
                            }
                        }
                    }

                    var account = service.PhoneLogin(user.account, password);
                    if (account != null)
                    {
                        string tokenValue = this.getGuidString();
                        wuliu_account_online online = new wuliu_account_online();
                        online.account_id = usermod.account_id;
                        online.online_key = tokenValue;
                        if (user.savetime > 0)
                        {
                            online.sdatetime = DateConvert.DateTimeToStamp(DateTime.Now);
                            online.edatetime = DateConvert.DateTimeToStamp(DateTime.Now.AddDays(user.savetime));
                        }
                        else
                        {
                            online.edatetime = DateConvert.DateTimeToStamp(DateTime.Now);
                            online.sdatetime = DateConvert.DateTimeToStamp(DateTime.Now.AddDays(1));
                        }

                        var fl = service.Add(online);

                        if (user.channel == "200")//安卓
                        {
                            wuliu_account_android_token android = new wuliu_account_android_token();
                            android.account_id = usermod.account_id;
                            android.android_token = user.registration_id;
                            android.create_time = DateConvert.DateTimeToStamp(DateTime.Now);
                            var fla = service.DelAndroidPhoneToken(usermod.account_id.ToString(), user.registration_id);
                            fla = service.DelIOSPhoneToken(usermod.account_id.ToString(), user.registration_id);
                            service.AddAndroidPhoneToken(android);
                        }
                        if(user.channel=="300")//IOS
                        {
                            wuliu_account_ios_token ios = new wuliu_account_ios_token();
                            ios.account_id = usermod.account_id;
                            ios.ios_token = user.registration_id;
                            ios.create_time = DateConvert.DateTimeToStamp(DateTime.Now);
                            var fla = service.DelAndroidPhoneToken(usermod.account_id.ToString(), user.registration_id);
                            fla = service.DelIOSPhoneToken(usermod.account_id.ToString(), user.registration_id);
                            service.AddIOSPhoneToken(ios);
                        }

                        Resultmod.InitResultState(LoginEnum.Success);
                        Resultmod.mod = account;
                        Resultmod.token = tokenValue;
                        CacheManager.TokenInsert(tokenValue, service.Login(usermod.account, password, ip));

                    }
                    else
                    {
                        Resultmod.InitResultState(LoginEnum.Error01);
                    }
                }
            }
           
            return Resultmod;
        }

        /// <summary>
        /// 通过凭证来获取菜单数据
        /// </summary>
        /// <param name="token"></param>
        /// <param name="jsonpCallback"></param>
        /// <returns></returns>
        [HttpGet]
        public HttpResponseMessage GetFirstMeum(string token,string menutype, string jsonpCallback)
        {
            if(menutype=="1"||menutype=="2"||menutype=="3")
            {

            }
            var Resultmod = new ResponseModel();
            StringBuilder str = new StringBuilder();
            str.Append(@"{'href':['#remain','#Standard_List','#wareshouse','#Waybill_List','#Report_List','#Business_List','#Standard_List_wm','#Waybill_List_wm'],'text':['待办首页','标单管理','仓管运单','运单管理','账单管理','企业中心','外贸标单','外贸运单']}");
            //str.Append(@"{'href':['#remain','#Standard_List','#wareshouse','#Waybill_List','#Report_List','#Business_List'],'text':['待办首页','标单管理','仓管运单','运单管理','账单管理','企业中心'],'icon':[1,2,3,4,5,6]}");
            string content = string.Format("{0}({1})", jsonpCallback, str);//new JavaScriptSerializer().Serialize(Resultmod)
            return new HttpResponseMessage(HttpStatusCode.OK)
            {
                Content = new StringContent(content, Encoding.UTF8, "text/javascript")
            };
        }
        [HttpGet]
        public HttpResponseMessage GetSendMeum(string token, string type, string jsonpCallback)
        {
            string str;
            switch (type)
            {
                case "1":
                    str = @"{
	
	'menu':[
		{
			'text':'标单列表',
			'href':'#standard_tablist'

		},
		{
			'text':'历史标单',
			'href':'#standard_history'
		}
	]
}
"; break;

                case "2":
                    {
                        str = @"{
	'menu':[
        {
			'text':'装货列表',
			'href':'#waybill_storelist'

		},
		{
			'text':'标单操作',
			'href':'#waybill_storelook'

		},
		{
			'text':'运单列表',
			'href':'#waybill_deliverylist'
		},
		{
			'text':'历史运单',
			'href':'#waybill_history'
		}
	]
}";
                    } break;
                case "4":
                      str = @"{
	
	'menu':[
		{
			'text':'未结帐单',
			'href':'#Checklist'

		},
		{
			'text':'已结帐单',
			'href':'#Checkedlist'
		}
	]
}
"; break;
                case "5":
                    {
                        str = @"
{

    'menu': [{
            'text': '企业信息管理',
            'href': '#',
            'list': [{
                'text': '基础设置',
                'href': '#base'
            }, {
                'text': '下属账号管理',
                'href': '#subordinate'
            }, {
                'text': '销售人员管理',
                'href': '#sale'
            }]

        }, {
            'text': '签约中心',
            'href': '#',
            'list': [{
                'text': '签约申请',
                'href': '#sign_apply'
            }, {
                'text': '签约授权',
                'href': '#sign_authorize'
            }, {
                'text': '签约管理',
                'href': '#sign_manage'
            }]
               }, {
            'text': '服务中心',
            'href': '#',
            'list': [{
                'text': '我的点评',
                'href': '#service_vote'
            }, {
                'text': '投诉调解',
                'href': '#service_mediate'
            }, {
                'text': '投诉调解记录',
                'href': '#service_record'
            }]
                  }, {
            'text': '公告管理',
            'href': '#',
            'list': [{
                'text': '企业公告',
                'href': '#history'
            }, {
                'text': '历史公告',
                'href': '#notice'
            }]
       }, {
            'text': '安全中心',
            'href': '#',
            'list': [{
                'text': '修改密码',
                'href': '#safe_pwd'
            }, {
                'text': '绑定手机',
                'href': '#safe_phone'
            }, {
                'text': '绑定邮箱',
                'href': '#safe_email'
            }]
        }

    ]
}
";
                    } break;

                case "6":
                    str = @"{
	
	'menu':[
		{
			'text':'标单列表',
			'href':'#standard_tablistwm'

		},
		{
			'text':'历史标单',
			'href':'#standard_historywm'
		}
	]
}
"; break;


                default:
                    str = ""; break;
            }
            string content = string.Format("{0}({1})", jsonpCallback, str);//new JavaScriptSerializer().Serialize(Resultmod)
            return new HttpResponseMessage(HttpStatusCode.OK)
            {
                Content = new StringContent(content, Encoding.UTF8, "text/javascript")
            };
        }

//        [HttpGet]
//        public HttpResponseMessage GetSendMeum(string token, string type, string jsonpCallback)
//        {
//            string str;
//            switch (type)
//            {
//                case "1":
//                    str = @"{
//	
//	'menu':[
//		{
//			'text':'标单列表',
//			'href':'#standard_tablist'
//
//		},
//		{
//			'text':'历史标单',
//			'href':'#standard_history'
//		}
//	]
//}
//"; break;

//                case "2":
//                    {
//                        str = @"{
//	'menu':[
//		{
//			'text':'装货查看',
//			'href':'#waybill_storelook'
//
//		},
//		{
//			'text':'装货列表',
//			'href':'#waybill_storelist'
//
//		},
//		{
//			'text':'运单列表',
//			'href':'#waybill_deliverylist'
//		},
//		{
//			'text':'历史运单',
//			'href':'#waybill_history'
//		}
//	]
//}";
//                    } break;
//                case "5":
//                    {
//                        str = @"
//{
//
//    'menu': [{
//            'text': '企业信息管理',
//            'href': '#',
//            'list': [{
//                'text': '基础设置',
//                'href': '#base'
//            }, {
//                'text': '下属账号管理',
//                'href': '#subordinate'
//            }, {
//                'text': '销售人员管理',
//                'href': '#sale'
//            }]
//
//        }, {
//            'text': '签约中心',
//            'href': '#',
//            'list': [{
//                'text': '签约申请',
//                'href': '#sign_apply'
//            }, {
//                'text': '签约授权',
//                'href': '#sign_authorize'
//            }, {
//                'text': '签约管理',
//                'href': '#sign_manage'
//            }]
//        }, {
//            'text': '服务中心',
//            'href': '#',
//            'list': [{
//                'text': '我的点评',
//                'href': '#service_vote'
//            }, {
//                'text': '投诉调解',
//                'href': '#service_mediate'
//            }, {
//                'text': '投诉调解记录',
//                'href': '#service_record'
//            }]
//        }, {
//            'text': '公告管理',
//            'href': '#',
//            'list': [{
//                'text': '企业公告',
//                'href': '#notice'
//            }, {
//                'text': '历史公告',
//                'href': '#history'
//            }]
//        }, {
//            'text': '安全中心',
//            'href': '#',
//            'list': [{
//                'text': '修改密码',
//                'href': '#safe_pwd'
//            }, {
//                'text': '绑定手机',
//                'href': '#safe_phone'
//            }, {
//                'text': '绑定邮箱',
//                'href': '#safe_email'
//            }]
//        }
//
//    ]
//}
//
//
//";
//                    } break;
//                default:
//                    str = ""; break;
//            }
//            string content = string.Format("{0}({1})", jsonpCallback, str);//new JavaScriptSerializer().Serialize(Resultmod)
//            return new HttpResponseMessage(HttpStatusCode.OK)
//            {
//                Content = new StringContent(content, Encoding.UTF8, "text/javascript")
//            };
//        }

        /// <summary>
        /// 检查用户凭证并返回用户数据
        /// </summary>
        /// <param name="token"></param>
        /// <returns></returns>
        /// <summary>
        /// 检查用户凭证并返回用户数据
        /// </summary>
        /// <param name="token"></param>
        /// <returns></returns>
        public ResponseModel CheckToken(string token)
        {
            object enty = CacheManager.GetTokenValue(token);
            var Resultmod = new ResponseModel();
            if (enty != null)
            {
                Resultmod.InitResultState(LoginEnum.Success);
                Resultmod.mod = enty;
                Resultmod.token = token;
            }
            else
            {
                var model = service.IsCheckUserToken(token, DateConvert.DateTimeToStamp(DateTime.Now));
                if (model != null)
                {
                    Resultmod.InitResultState(LoginEnum.Success);
                    Resultmod.mod = service.GetByAccountId(model.account_id.ToString());
                    Resultmod.token = token;
                }
                else
                {
                    Resultmod.InitResultState(LoginEnum.Error80);
                }

            }
            return Resultmod;
        }

        /// <summary>
        /// token获取
        /// </summary>
        /// <param name="token"></param>
        /// <returns></returns>
        [HttpGet]
        public ResponseModel GetIsExistToken(string token)
        {
            ResponseModel mod = new ResponseModel();
            mod.InitResultState(BoolEnum.True);
            var fla = CacheManager.TokenIsExist(token);
            if (!fla)
            {
                var model = service.IsCheckUserToken(token, DateConvert.DateTimeToStamp(DateTime.Now));
                fla = model.account_id.ToInt32(0) > 0;
            }
            mod.resmessage = fla.ToString();
            return mod;
        }

        /// <summary>
        /// 通过凭证退出系统清空凭证
        /// </summary>
        /// <param name="token"></param>
        /// <returns></returns>
        [HttpPost]
        public ResponseModel PhoneLoginOut(wuliu_account_base_query account)
        {
            var tokenflag = CacheManager.TokenClear(account.token);
            var Resultmod = new ResponseModel();
            try
            {
                var usermod = service.GetAccountById(account.account);
                if (account.channel != null)
                {
                    if (account.channel == "200")
                    {
                        var fla = service.DelAndroidPhoneToken(usermod.account_id.ToString(), account.registration_id);

                    }
                    if (account.channel == "300")
                    {
                        var fla = service.DelIOSPhoneToken(usermod.account_id.ToString(), account.registration_id);
                    }
                    if (account.channel != "200" && account.channel != "300")
                    {
                        var fla = service.DelAndroidPhoneToken(usermod.account_id.ToString(), account.registration_id);
                        fla = service.DelIOSPhoneToken(usermod.account_id.ToString(), account.registration_id);
                    }
                }
                else
                {
                    var fla = service.DelAndroidPhoneToken(usermod.account_id.ToString(), account.registration_id);
                    fla = service.DelIOSPhoneToken(usermod.account_id.ToString(), account.registration_id);
                }
                

                wuliu_account_online online = new wuliu_account_online();
                online.account_id = usermod.account_id;
                online.online_key = "";
                var flag = service.Add(online);
                Resultmod.InitResultState(LoginOutEnum.Success);
                Resultmod.mod = flag;

            }
            catch (Exception ex)
            {
                Resultmod.InitResultState(ex);
            }
            

            return Resultmod;
        }

        /// <summary>
        /// 通过凭证退出系统清空凭证
        /// </summary>
        /// <param name="token"></param>
        /// <returns></returns>
        [HttpPost]
        public ResponseModel LoginOut(string token, string account)
        {
            var tokenflag = CacheManager.TokenClear(token);
            var usermod = service.GetAccountById(account);
            //var accountId = Convert.ToInt32(HttpContext.Current.Request.Headers[LogisticsConst.LOGIN_HEADER]);
            var Resultmod = new ResponseModel();
            if (tokenflag)
            {
                wuliu_account_online online = new wuliu_account_online();
                online.account_id = usermod.account_id;
                online.online_key_pc = "";
                var flag = service.Add(online);
                Resultmod.InitResultState(LoginOutEnum.Success);
                Resultmod.mod = flag;
            }
            else
            {
                Resultmod.InitResultState(LoginOutEnum.Error01);
            }

            return Resultmod;
        }
        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        [MyAuthority]
        [HttpPost]
        public ResponseModel GetList(PageQuery page)
        {
            if (page == null)
                page = new PageQuery();
            var resultmod = new ResponseModel();
            AccountService service = new AccountService();
            var accountId = Convert.ToInt32(HttpContext.Current.Request.Headers[LogisticsConst.LOGIN_HEADER]);
            int company_id = companyService.GetCompanyIdByAccountId(accountId);
            try
            {
                resultmod.mod = service.GetListByCompanyId(company_id,page.page-1,page.pagesize);
                resultmod.InitResultState(GetDataStateEnum.Success);
            }
            catch (Exception ex)
            {

                resultmod.InitResultState(ex);
            }

            return resultmod;
        }

        [MyAuthority]
        [HttpPost]
        public ResponseModel GetContactsList()
        {
            var resultmod = new ResponseModel();
            AccountService service = new AccountService();
            var accountId = Convert.ToInt32(HttpContext.Current.Request.Headers[LogisticsConst.LOGIN_HEADER]);
            int company_id = companyService.GetCompanyIdByAccountId(accountId);
            try
            {
                resultmod.mod = service.GetContactsList(company_id);
                resultmod.InitResultState(GetDataStateEnum.Success);
            }
            catch (Exception ex)
            {

                resultmod.InitResultState(ex);
            }

            return resultmod;
        }

        /// <summary>
        /// 产生绝对唯一字符串，用于令牌
        /// </summary>
        /// <returns></returns>
        private string getGuidString()
        {
            return getMd5Hash(Guid.NewGuid().ToString());
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="flag"></param>
        /// <returns></returns>
         [HttpPost]
         [MyAuthority]
        public ResponseModel GetAccountInfo(wuliu_account_base_query account)
        {
            var resultmod = new ResponseModel();
            var usermod = service.GetAccountById(account.account);
            if (usermod!=null)
            {
                resultmod.InitResultState(StateEnum.Success);
            }
            else
            {
                resultmod.InitResultState(StateEnum.Error);
            }
            resultmod.mod = usermod;
            return resultmod;

        }



        // GET api/<controller>/5
        public string Index()
        {
            return "hello world!";
        }



        /// <summary>
        /// 新增
        /// </summary>
        /// <param name="account"></param>
        /// <returns></returns>
        [HttpPost]
        [MyAuthority]
        public ResponseModel Add(wuliu_account_base_query account)
        {
            var resultmod = new ResponseModel();
            try
            {
                var accountId = Convert.ToInt32(HttpContext.Current.Request.Headers[LogisticsConst.LOGIN_HEADER]);
                var company = companyService.GetCompanyByAccountId(accountId);
                MD5 md5 = MD5.Create();
                AccountService service = new AccountService();
                account.password = getMd5Hash(account.password);
                account.type = "10";
                account.password_type = 11;
                account.user_type = "1";
                account.state = 1;
                account.company_id = company.company_id;
                account.company_name = company.company_name;
                account.company_no = company.company_no;
                var result = service.Add(account);
                resultmod.mod = result;
                if (result)
                {
                    resultmod.InitResultState(StateEnum.Success);
                }
                else
                {
                    resultmod.InitResultState(StateEnum.Error);
                }
            }
            catch (Exception ex)
            {
                resultmod.InitResultState(ex);
            }
            return resultmod;
        }

        /// <summary>
        /// 修改密码
        /// </summary>
        /// <param name="account"></param>
        /// <returns></returns>
        [HttpPost]
        public ResponseModel EditEmailAndPhone(wuliu_account_query account)
        {
            var resultmod = new ResponseModel(); var result = false;
            wuliu_account_base useraccount = new wuliu_account_base();
            var usermod = service.GetAccountById(account.account);
            useraccount.account_id = usermod.account_id;
            if(account.email!=null)
            {
                useraccount.email = account.email;
                result = service.Update(useraccount);
            }
            if(account.phone!=null)
            {
                var num = service.IsExistPhone(account.phone);
                if(num==0)
                {
                    useraccount.phone = account.phone;
                    result = service.Update(useraccount);
                }
            }
            if(account.nick_name!=null)
            {
                useraccount.nick_name = account.nick_name;
                result = service.Update(useraccount);
            }
            if(account.newpassword!=null&&account.password!=null)
            {
                string password = account.password;
                if (usermod != null)
                {
                    if (usermod.password_type == 11)
                    {
                        password = getMd5Hash(usermod.password_key + account.newpassword);
                    }
                    else
                    {
                        if (usermod.password_type == 0)
                        {
                            password = account.newpassword;
                        }
                        else
                        {
                            password = getMd5Hash(account.newpassword);
                        }
                    }
                    useraccount.account_id = usermod.account_id;
                    useraccount.password = password;
                    result = service.Update(useraccount);
                }
            }
             
            if (result)
            {
                resultmod.InitResultState(StateEnum.Success);
            }
            else
            {
                resultmod.InitResultState(StateEnum.Error);
            }
            resultmod.mod = result;
            return resultmod;
        }
        /// <summary>
        /// 修改密码
        /// </summary>
        /// <param name="account"></param>
        /// <returns></returns>
        [HttpPost]
        public ResponseModel EditPassWord(wuliu_account_query account)
        {
            var resultmod = new ResponseModel(); MD5 md5 = MD5.Create();
            try
            {
                wuliu_account_base useraccount = new wuliu_account_base();
                var usermod = service.GetAccountById(account.account);
                string password = account.password;
                if (usermod != null)
                {
                    if (usermod.password_type == 11)
                    {
                        password = getMd5Hash(usermod.password_key + account.newpassword);
                    }
                    else
                    {
                        if (usermod.password_type == 0)
                        {
                            password = account.newpassword;
                        }
                        else
                        {
                            password = getMd5Hash(account.newpassword);
                        }
                    }
                    useraccount.account_id = usermod.account_id;
                    useraccount.password = password;
                    var result = service.Update(useraccount);
                    if (result)
                    {
                        resultmod.InitResultState(StateEnum.Success);
                    }
                    else
                    {
                        resultmod.InitResultState(StateEnum.Error);
                    }
                }
                else
                    resultmod.InitResultState(StateEnum.Error);
            }
            catch (Exception ex)
            {
                resultmod.InitResultState(ex);
            }
            
            
            return resultmod;
        }

        /// <summary>
        /// 更新帐号
        /// </summary>
        /// <param name="account"></param>
        /// <returns></returns>
        [HttpPost]
        [MyAuthority]
        public ResponseModel Update(wuliu_account_base_query account)
        {
            var responseModel = new ResponseModel();
            try
            {
                MD5 md5 = MD5.Create();
                AccountService service = new AccountService();
                account.password = getMd5Hash(account.password);
                var result = service.Update(account);
                responseModel.mod = result;
                if (result)
                {
                    responseModel.InitResultState(StateEnum.Success);
                }
                else
                {
                    responseModel.InitResultState(StateEnum.Error);
                }
            }
            catch (Exception ex)
            {
                responseModel.InitResultState(ex);
            }
            return responseModel;
        }

        [HttpGet]
        public ResponseModel UpdateState(int id,int state)
        {
            var responseModel = new ResponseModel();
            try
            {
              
                AccountService service = new AccountService();
                var result = service.UpdateState(id,state);
                responseModel.mod = result;
                if (result>0)
                {
                    responseModel.InitResultState(StateEnum.Success);
                }
                else
                {
                    responseModel.InitResultState(StateEnum.Error);
                }
            }
            catch (Exception ex)
            {
                responseModel.InitResultState(ex);
            }
            return responseModel;
        }

        static string getMd5Hash(string input)
        {
            // Create a new instance of the MD5CryptoServiceProvider object.  
            MD5 md5Hasher = MD5.Create();

            // Convert the input string to a byte array and compute the hash.  
            byte[] data = md5Hasher.ComputeHash(Encoding.Default.GetBytes(input));

            // Create a new Stringbuilder to collect the bytes  
            // and create a string.  
            StringBuilder sBuilder = new StringBuilder();

            // Loop through each byte of the hashed data   
            // and format each one as a hexadecimal string.  
            for (int i = 0; i < data.Length; i++)
            {
                sBuilder.Append(data[i].ToString("x2"));
            }

            // Return the hexadecimal string.  
            return sBuilder.ToString();
        }
    }
}